package net.huashitong.Indicators.schedule;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.huashitong.Indicators.entity.CompletionClassification;
import net.huashitong.Indicators.entity.EarlyWarning;
import net.huashitong.Indicators.entity.TertiaryIndustry;
import net.huashitong.Indicators.filter.IndicatorBreakdownFilter;
import net.huashitong.Indicators.service.CompletionClassificationService;
import net.huashitong.Indicators.service.EarlyWarningService;
import net.huashitong.Indicators.service.IndicatorBreakdownService;
import net.huashitong.Indicators.service.TertiaryIndustryService;
import net.huashitong.Indicators.utils.DateForIndUtils;

import org.apache.shiro.SecurityUtils;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.orm.hibernate4.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.sirdc.modules.core.web.bind.SpringContextHolder;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.ObjectUtils;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;

public class EarlyWarningSchedule {
	@Autowired
	private TertiaryIndustryService industryService;
	@Autowired
	private IndicatorBreakdownService breakdownService;
	@Autowired
	private CompletionClassificationService classificationService;
	@Autowired
	private EarlyWarningService earlyWarningService;
	@Autowired
	private SysUserService sysUserService;
	
	private final static String apiKey= "b3232c91e3336d52ae80b73bb0a1cb91";
	@Autowired
	org.apache.shiro.mgt.SecurityManager securityManager;
	public synchronized void onStart() throws ParseException{	
		SessionFactory sessionFactory = (SessionFactory)SpringContextHolder.getBean("sessionFactory"); 
		boolean participate = bindHibernateSessionToThread(sessionFactory);
		//securityManager();
		SecurityUtils.setSecurityManager(securityManager);
		EarlyWarningSch();  
		System.out.println("--------------定时任务执行完毕--------------------");
		closeHibernateSessionFromThread(participate, sessionFactory); 
	}

	/**
	 * 处理是否预警
	 * @throws ParseException 
	 */
	public void EarlyWarningSch() throws ParseException {
		IndicatorBreakdownFilter filter = new IndicatorBreakdownFilter();
		filter.setArea("永泰县");
		filter.setDate(DateForIndUtils.getNextMonthValueDate(new Date().toString(), 0));
		filter.setCurrentMonth(DateForIndUtils.getNextMonthDate(new Date().toString(), 0));
		filter.setQy("企业");
		filter.setXz("乡镇");
		filter.setHy("行业");
		filter.setBm("部门");
		filter.setIndustryName("固定资产投资");
		filter.setIndustryId("A07");
		String date = DateForIndUtils.getNextMonthValueDate(DateForIndUtils.getCurDate("yyyyMM-MM"), 0);
		String cdate = 	DateForIndUtils.getNextMonthDate(DateForIndUtils.getCurDate("yyyyMM"), 0);
		//固投50w乡镇
		boolean yesOrNot = getXZByGT(filter);
		if(yesOrNot == true){
			filter.setPosition("5");
			filter.setDate(date);
			String type = filter.getXz();
			saveEarlyWarning(filter,type);
		}
		//固投部门
		filter.setDate(date);
		filter.setCurrentMonth(cdate);
		yesOrNot = getBMByGT(filter);
		if(yesOrNot == true){
			filter.setPosition("5");
			filter.setDate(date);
			filter.setCurrentMonth(cdate);
			String type = filter.getBm();
			saveEarlyWarning(filter,type);
		}
		//固投企业
		filter.setDate(date);
		filter.setCurrentMonth(cdate);
		yesOrNot = getQYByGT(filter);
		if(yesOrNot == true){
			filter.setPosition("7");
			filter.setDate(date);
			filter.setCurrentMonth(cdate);
			String type = filter.getQy();
			saveEarlyWarning(filter,type);
		}
		filter.setIndustryName("规模以上工业增加值");
		filter.setIndustryId("A05");
		//规上乡镇
		filter.setDate(date);
		filter.setCurrentMonth(cdate);
		yesOrNot = getXZByGS(filter);
		if(yesOrNot == true){
			filter.setPosition("5");
			filter.setDate(date);
			filter.setCurrentMonth(cdate);
			String type = filter.getXz();
			saveEarlyWarning(filter,type);
		}
		//规上行业
		filter.setDate(date);
		filter.setCurrentMonth(cdate);
		yesOrNot = getHYByGS(filter);
		if(yesOrNot == true){
			filter.setPosition("10");
			filter.setDate(date);
			filter.setCurrentMonth(cdate);
			String type = filter.getHy();
			saveEarlyWarning(filter,type);
		}
		filter.setIndustryName("建筑业增加值");
		filter.setIndustryId("A04");
		//建筑业企业
		filter.setDate(date);
		filter.setCurrentMonth(cdate);
		yesOrNot = getQYByJZY(filter);
		if(yesOrNot == true){
			filter.setPosition("5");
			filter.setDate(date);
			filter.setCurrentMonth(cdate);
			String type = filter.getQy();
			saveEarlyWarning(filter,type);
		}
		filter.setIndustryName("社会消费品零售总额");
		filter.setIndustryId("A13");
		//社零乡镇
		filter.setDate(date);
		filter.setCurrentMonth(cdate);
		yesOrNot = getXZBySL(filter);
		if(yesOrNot == true){
			filter.setPosition("5");
			filter.setDate(date);
			filter.setCurrentMonth(cdate);
			String type = filter.getXz();
			saveEarlyWarning(filter,type);
		}
	}
	
	
	public void saveEarlyWarning(IndicatorBreakdownFilter filter, String type) {
		EarlyWarning earlyWarning = new EarlyWarning();
		earlyWarning.setArea(filter.getArea());
		earlyWarning.setIndustryName(filter.getIndustryId());
		earlyWarning.setIndustryName(filter.getIndustryName());
		earlyWarning.setDate(filter.getDate());
		earlyWarning.setTitle(filter.getDate().substring(2, 4)+"年"+filter.getCurrentMonth().substring(4)+"月"+filter.getIndustryName()+type+"预警情况");
		earlyWarning.setChartPosition(filter.getPosition());
		earlyWarning.setIndicatorId("");
		earlyWarningService.save(earlyWarning);
		
		TertiaryIndustry industry = industryService.getById(filter.getIndustryId());
		String[] names = industry.getLeadership().split("、");
		List<SysUser> sysUsers = sysUserService.getByInName(names);
		for (SysUser sysUser : sysUsers) {
//			YunpianClient clnt = new YunpianClient(apiKey).init();
//	    	//修改账户信息API
//	    	Map<String, String> param = clnt.newParam(2);
//	    	param.put(YunpianClient.MOBILE, sysUser.getMobile());
//	    	param.put(YunpianClient.TEXT, "【经济指标管理系统】"+filter.getDate().substring(2, 4)+"年"+filter.getCurrentMonth().substring(4)+"月"+filter.getIndustryName()+type+"出现异常请前往查看!");
//	    	Result<SmsSingleSend> r = clnt.sms().single_send(param);
//	    	//获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
//	    	//账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
//	    	//最后释放client
//	    	clnt.close();
		}
	}

	//社零乡镇
	public boolean getXZBySL(IndicatorBreakdownFilter filter) {
		List<CompletionClassification> classification2s = classificationService.queryByXZValue(filter);
		if(ObjectUtils.isBlank(classification2s)){
			return false;
		}
		for (CompletionClassification completionClassification : classification2s) {
			Double doublebs1 = Double.parseDouble(completionClassification.getActualCompletionValue());
			Double doublebs2 = Double.parseDouble(completionClassification.getPlanneValue());
			Double doublebs3 = doublebs1/doublebs2*100;
			if(doublebs3<50){
				return true;
			}
		}
		return false;
	}

	//建筑业企业
	public boolean getQYByJZY(IndicatorBreakdownFilter filter) {
		List<CompletionClassification> classificationds = classificationService.queryByDWYearValue(filter);
		if(ObjectUtils.isBlank(classificationds)){
			return false;
		}
		for (CompletionClassification completionClassification : classificationds) {
			Double double1 = (Double.parseDouble(completionClassification.getActualCompletionValue())/10000)/(Double.parseDouble(completionClassification.getPlanneValue())/10000)*100;
			if(double1 < 70){
				return true;
			}
		}
		return false;
	}
	//规上行业
	public boolean getHYByGS(IndicatorBreakdownFilter filter) throws ParseException {
		List<CompletionClassification> classification3s = classificationService.queryByHYValueSec(filter);
		if(ObjectUtils.isBlank(classification3s)){
			return false;
		}
		filter.setDate(DateForIndUtils.getNextMonthValueDate(filter.getDate(), -1));
		List<CompletionClassification> classifications = classificationService.queryByHYValueSec(filter);
		for (CompletionClassification completionClassification : classification3s) {
			for (CompletionClassification completionClassification2 : classifications) {
				if(completionClassification.getCategoryDetails().equals(completionClassification2.getCategoryDetails())){
					Double double1 = Double.parseDouble(completionClassification.getSpecificIncrease());
					if(double1 < 0){
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 规上乡镇
	 * @param filter
	 * @return
	 */
	public boolean getXZByGS(IndicatorBreakdownFilter filter) {
		List<CompletionClassification> classification2s = classificationService.queryByXZValue(filter);
		if(ObjectUtils.isBlank(classification2s)){
			return false;
		}
		for (CompletionClassification completionClassification : classification2s) {
			Double doublebs1 = Double.parseDouble(completionClassification.getActualCompletionValue());
			Double doublebs2 = Double.parseDouble(completionClassification.getPlanneValue());
			Double doublebs3 = doublebs1/doublebs2*100;
			if(doublebs3<41){
				return true;
			}
		}
		return false;
	}

	/**
	 * 固投企业
	 * @param filter
	 * @return
	 */
	public boolean getQYByGT(IndicatorBreakdownFilter filter) {
		List<CompletionClassification> classificationds = classificationService.queryByDWValue(filter);
		if(ObjectUtils.isBlank(classificationds)){
			return false;
		}
		for (CompletionClassification completionClassification : classificationds) {
			Double doubleds1 = Double.parseDouble(completionClassification.getActualCompletionValue());
			Double doubleds2 = Double.parseDouble(completionClassification.getPlanneValue());
			Double doubleds3 = doubleds1/doubleds2*100;
			if(doubleds3<50){
				return true;
			}
		}
		return false;
	}

	/**
	 * 固投部门
	 * @param filter
	 * @return
	 */
	public boolean getBMByGT(IndicatorBreakdownFilter filter) {
		List<CompletionClassification> classifications = classificationService.queryByValue(filter);
		if(ObjectUtils.isBlank(classifications)){
			return false;
		}
		for (CompletionClassification completionClassification : classifications) {
			Double doublebs1 = Double.parseDouble(completionClassification.getActualCompletionValue());
			Double doublebs2 = Double.parseDouble(completionClassification.getPlanneValue());
			Double doublebs3 = doublebs1/doublebs2*100;
			if(doublebs3<50){
				return true;
			}
		}
		return false;
	}

	/**
	 * 固投50w乡镇
	 * @param filter
	 * @return
	 */
	public boolean getXZByGT(IndicatorBreakdownFilter filter) {
		List<CompletionClassification> classification2s = classificationService.queryByXZValue(filter);
		if(ObjectUtils.isBlank(classification2s)){
			return false;
		}
		for (CompletionClassification completionClassification : classification2s) {
			Double doublebs1 = Double.parseDouble(completionClassification.getActualCompletionValue());
			Double doublebs2 = Double.parseDouble(completionClassification.getPlanneValue());
			Double doublebs3 = doublebs1/doublebs2*100;
			if(doublebs3<50){
				return true;
			}
		}
		return false;
	}

	private void closeHibernateSessionFromThread(boolean participate,
			SessionFactory sessionFactory) {
		if (!participate) {
			SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
					.unbindResource(sessionFactory);
			SessionFactoryUtils.closeSession(sessionHolder.getSession());
		}
		
	}

	private boolean bindHibernateSessionToThread(SessionFactory sessionFactory) {
		if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
			// Do not modify the Session: just set the participate flag.
			return true;
		} else {
			Session session = sessionFactory.openSession();
			session.setFlushMode(FlushMode.MANUAL);
			SessionHolder sessionHolder = new SessionHolder(session);
			TransactionSynchronizationManager.bindResource(sessionFactory,
					sessionHolder);
		}
		return false;
	}
}
